package com.lixiaoyi.emp.dao.impl;

import com.lixiaoyi.emp.dao.IEmpDao;
import com.lixiaoyi.emp.entity.Emp;
import com.lixiaoyi.emp.entity.Page;
import com.lixiaoyi.emp.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author 李小毅
 * @Description
 * @Date 2022-05-12
 */

public class EmpDaoImpl implements IEmpDao {

    private QueryRunner queryRunner = new QueryRunner(DbUtils.getDs());

    @Override
    public List<Emp> selectAll() {
        try {
            List<Emp> emps = queryRunner.query(DbUtils.getConnection(),"select * from emp; ",new BeanListHandler<Emp>(Emp.class));

            return emps;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int delete(int id) {
        try {
            int result = queryRunner.update(DbUtils.getConnection(), "delete from emp where id = ?;", id);
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int update(Emp emp) {
        try {
            int result = queryRunner.update(DbUtils.getConnection(),"update emp set name=?,salary=?,age=? where id =?",emp.getName(),emp.getSalary(),emp.getAge(),emp.getId());
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Emp select(int id) {
        try {
            Emp emp =  queryRunner.query(DbUtils.getConnection(),"select * from emp where id =?",new BeanHandler<Emp>(Emp.class),id);

            return emp;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Emp add() {

        try {
            Emp emp = queryRunner.insert(DbUtils.getConnection(),"insert into emp(id,name,salary,age) values(?,'?',?,?)",new BeanHandler<Emp>(Emp.class));

            return emp;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Emp> selectByPage(Page page) {

        try {
            List<Emp> emps = queryRunner.query(DbUtils.getConnection(),"select * from emp limit ?,?",new BeanListHandler<Emp>(Emp.class),page.getStartRows(),page.getPageSize());
            return emps;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public long selectCount() {
        try {
            return queryRunner.query(DbUtils.getConnection(),"select count(*) from emp",new ScalarHandler<>());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
